package com.ctrip.corp.obt.shard.loader;


import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.shard.constants.SourceLoadMode;
import com.ctrip.corp.obt.shard.manager.DataShardSourceManager;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.Set;

/**
 * @author marco.zheng
 * @version 1.0
 * @date 2022/01/14
 * @desc 控制面数据分片加载器
 * @see
 * @since 1.0
 */
@Slf4j
public class CPShardSourceLoader extends AbstractShardSourceLoader {

    public CPShardSourceLoader(DataShardSourceManager dataShardSourceManager) {
        super(dataShardSourceManager);
    }

    /**
     * Startup加载
     *
     * @return
     */
    @Override
    public void loadOnStartup() {
        getDataShardSourceManager().initDataSource();
        log.info("Startup loading shard source, source load mode:[{}]", SourceLoadMode.CONTROL_PLANE);
    }

    @Override
    public void refresh(String tenantId) {
        loadBySources(Collections.singleton(tenantId));
    }

    /**
     * 指定分组加载(后期客户量大，每个pod只能按照策略加载有限的ds)
     * 可通过control plane进行分配
     *
     * @return
     */
    @Override
    public Set<String> loadBySources(Set<String> tenantIds) {
        if (CollectionUtils.isEmpty(tenantIds)) {
            return Collections.emptySet();
        }
        DataShardSourceManager dataShardSourceManager = getDataShardSourceManager();
        Set<String> finishLoadSources = dataShardSourceManager.cacheShardSource(tenantIds);
        log.info("Load limited shard source, source num:[{}]", finishLoadSources.size());
        if (CollectionUtils.isNotEmpty(finishLoadSources)) {
            dataShardSourceManager.initDataSource();
            return finishLoadSources;
        }
        return finishLoadSources;
    }

}
